package top.mcwebsite.playandroid.common.user.impl

import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
import top.mcwebsite.playandroid.common.network.api.NetworkService
import top.mcwebsite.playandroid.common.network.api.createApi
import top.mcwebsite.playandroid.common.user.api.IUserService
import top.mcwebsite.playandroid.common.user.api.model.UserData
import top.mcwebsite.playandroid.common.user.impl.api.UserApi
import top.mcwebsite.playandroid.lib.servicemanager.core.ServiceManager
import top.mcwebsite.playandroid.lib.servicemanager.core.annoation.ServiceImpl

@ServiceImpl(IUserService::class, isSingleton = true)
class UserServiceImpl : IUserService {

    private var cachedUserData: UserData? = null

    private var isLogin = false

    private val loginStateFlow = MutableStateFlow(false)

    override fun init() {
        val cookie = ServiceManager.getService<NetworkService>().getCookies()
        setLogin(cookie.isNotEmpty())
    }

    override fun isLogin(): Boolean {
        // TODO 通过 cookie 来判断是否登录，以及登录的有效期等等信息
        return isLogin
    }

    override fun isLoginFlow(): Flow<Boolean> {
        return loginStateFlow.asStateFlow()
    }

    override fun getCachedUserData(): UserData? {
        return cachedUserData
    }

    override suspend fun getUserInfo(): UserData {
        val userDataResp =
            ServiceManager.getService<NetworkService>().createApi<UserApi>().getUserData()

        if (userDataResp.errorCode != 0) {
            throw IllegalStateException("需要登录")
        }
        return userDataResp.data ?: throw IllegalStateException("未知错误")
    }

    override fun setLogin(isLogin: Boolean) {
        this.isLogin = isLogin
        CoroutineScope(Dispatchers.Main).launch {
            loginStateFlow.emit(isLogin)
        }
    }

    override suspend fun logout() {
        ServiceManager.getService<NetworkService>().clearCookies()
        setLogin(false)
        ServiceManager.getService<NetworkService>().createApi<UserApi>().logout()
    }


}